/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.freedoit;

import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.Properties;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import org.apache.log4j.Logger;
import org.freedoit.common.util.FreeDoitDataUtils;
import org.freedoit.util.Constants;
import org.freedoit.util.LogUtils;

/**
 *
 * @author wanglei
 */
public class FreeDoitConfig {

    private static final Logger logger = 
            LogUtils.getLogger(FreeDoitConfig.class);

    public static final String KEY_LAST_USER_NAME = "doit.last.user.name";
    public static final String KEY_LAST_KEY = "doit.last.key";
    public static final String KEY_USER_LIST = "doit.user.list";
    public static final String KEY_LOCALE = "doit.locale";
    public static final String KEY_SYNC_FREQ = "doit.sync.freq";

    public static final String SERVICE_URL = "http://freedoit.cloudfoundry.com/service/";
    public static final String ADD_TASK_SERVICE = SERVICE_URL + "addTask";
    public static final String UPDATE_TASK_SERVICE = SERVICE_URL + "updateTask";
    public static final String FINISH_TASK_SERVICE = SERVICE_URL + "finishTask";
    public static final String DELETE_TASK_SERVICE = SERVICE_URL + "deleteTask";
    public static final String SYNC_TASK_SERVICE = SERVICE_URL + "syncTask";
    public static final String SEND_TASK_SERVICE = SERVICE_URL + "sendTask";
    public static final String RECEIVE_TASK_SERVICE = SERVICE_URL + "receiveTask";
    public static final String SEND_RECEIVE_TASK_SERVICE = SERVICE_URL + "sendReceiveTask";
    public static final String AUTH_SERVICE = SERVICE_URL + "auth";
    
    public static final String FONT_NAME = "simsun";
    public static final String PLUGIN_FONT_NAME = "freedoit.ttc";
    
    
    private static final String RESOURCE_FILE_NAME_FORMAT = 
            "/resources/lang/freedoit_lang%s%s.properties";
    
    private static final String SPLIT_SYMBOL = ";";

    private static FreeDoitConfig singleton = new FreeDoitConfig();
    
    private Properties cachedProps = new Properties();
    
    private String configDir = ".";
    
    private String filename;
    
    private ResourceBundle resb1;
    
    private Font freedoitFont;
    
    private FreeDoitConfig() {
//        String userDir = System.getProperty("user.home");
//        if (userDir == null) {
//            userDir = ".";
//        }
        
        String dir = LogUtils.FREEDOIT_CONFIG_DIR;
        File fDir = new File(dir);
        if (!fDir.exists() && !fDir.mkdirs()) { // not exist, then create but if failed. exit.
            logger.error("Cannot create directory:" + dir);
            System.exit(-1);
        }
        
        configDir = dir;
        
        // ini file
        filename = dir + File.separator + "doit.ini";
        File f = new File(filename);

        if (f.exists() && f.canRead()) {
            try {
                cachedProps.load(new FileInputStream(f));
            } catch (IOException ex) {
                logger.error(ex);
            }
        }
        
        loadResourceBundle();
        
        // Load font
        loadFont();
    }
    
    private void loadResourceBundle()
    {
        String locale = cachedProps.getProperty(KEY_LOCALE);
        String resourceFileName = null;
        if (locale == null || "".equals(locale)) {
            resourceFileName = String.format(RESOURCE_FILE_NAME_FORMAT, "", "");
        } else {
            resourceFileName = String.format(RESOURCE_FILE_NAME_FORMAT, "_", locale);
        }

        System.out.println("Pre:" + resourceFileName);
        InputStream is = this.getClass().getResourceAsStream(resourceFileName);
        if (is == null) { // use default
            System.out.println("Again:" + resourceFileName);
            is = this.getClass().getResourceAsStream(
                    String.format(RESOURCE_FILE_NAME_FORMAT, "", ""));
        }
        try {
            resb1 = new PropertyResourceBundle(is);
    //                initLocale(cachedProps.getProperty(KEY_LOCALE)));
    //                initLocale(cachedProps.getProperty(KEY_LOCALE)));
        } catch (IOException ex) {
            logger.error(ex);
            System.exit(-1);
        }
    }
    
    public static String getLanguage() {
        String strLocale = singleton.cachedProps.getProperty(KEY_LOCALE);
        if (strLocale != null) {
            String[] langAndCountry = strLocale.split("-");
            if (langAndCountry != null && langAndCountry.length == 2) {
                return langAndCountry[0];
            }
        }
        
        return null;
    }
    
    private void loadFont() {
        // Scan system font
        Font[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
        if (fonts != null && fonts.length > 0) {
            for (Font f : fonts) {
                if (FONT_NAME.equals(f.getName().toLowerCase())) {
                    freedoitFont = f;
                    System.out.println(f.getName());
                    break;
                }
            }
        }
//        try {
//            freedoitFont = Font.createFont(Font.TRUETYPE_FONT,
//                    getClass().getResourceAsStream("/resources/font/freedoit.ttc"));
//        } catch (FontFormatException ex) {
//            Logger.getLogger(FreeDoitConfig.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (IOException ex) {
//            Logger.getLogger(FreeDoitConfig.class.getName()).log(Level.SEVERE, null, ex);
//        }
        
        
        if (freedoitFont == null) {
            freedoitFont = new Font(null, 0, 11);
        }
    }
    
    public static Font getFont(int style, float size) {
        if (singleton.freedoitFont == null) {
            return null;
        } else {
            return singleton.freedoitFont.deriveFont(style, size);
        }
    }
    
    public static Font getDefaultFont() {
        if (singleton.freedoitFont == null) {
            return null;
        } else {
            return singleton.freedoitFont.deriveFont(0, 11);
        }
    }
    
    private Locale initLocale(String strLocale) {
        Locale locale = Locale.getDefault();
        
        if (strLocale != null) {
            String[] langAndCountry = strLocale.split("-");
            if (langAndCountry != null && langAndCountry.length == 2) {
                locale = new Locale(langAndCountry[0], langAndCountry[1]);
            }
        }
        
        return locale;
    }

    static void saveConfig() {
        singleton.save();
    }
    
    private void save() {
        File f = new File(filename);
        try {
            if (!f.canWrite()) {
                f.createNewFile();
            }
            cachedProps.store(new FileOutputStream(filename), "freedoit configuration");
        } catch (FileNotFoundException ex) {
            logger.error(ex);
        } catch (IOException ex) {
            logger.error(ex);
        }
    }
    
    public static String getConfigDir() {
        return singleton.configDir;
    }

    private static String getProperty(String key) {
    	//
        return singleton.cachedProps.getProperty(key);
    }

    private static boolean setProperty(String key, String value) {
        singleton.cachedProps.put(key, value);
        return true;
    }

    private static boolean tryAddUser(String userName) {
    	//
        String value = singleton.cachedProps.getProperty(KEY_USER_LIST);
        if (value == null || "".endsWith(value)) {
            singleton.cachedProps.setProperty(KEY_USER_LIST, userName);
            return true;
        } else {
            String[] userList = value.split(SPLIT_SYMBOL);
            boolean userExisted = false;
            for (String s : userList) {
                if (s.equals(userName)) {
                    userExisted = true;
                    break;
                }
            }
            
            if (!userExisted) {
                value = value + SPLIT_SYMBOL + userName;
                singleton.cachedProps.setProperty(KEY_USER_LIST, value);
                return true;
            } else {
                return false;
            }
        }
    }

    public static boolean userNameExist(String userName) {
    	//
        String value = singleton.cachedProps.getProperty(KEY_USER_LIST);
        if (value == null || "".endsWith(value)) {
            return false;
        } else {
            String[] userList = value.split(SPLIT_SYMBOL);
            boolean userExisted = false;
            for (String s : userList) {
                if (s.equals(userName)) {
                    userExisted = true;
                    break;
                }
            }
            return userExisted;
        }
    }

    public static String getText(String key) {
        return singleton.resb1.getString(key);
    }

    public static String getText(String key, String charset) {
        String text = singleton.resb1.getString(key);
        if (text == null) {
            return null;
        }
        try {
            text = new String(text.getBytes(charset), charset);
        } catch (UnsupportedEncodingException ex) {
            logger.error(ex);
        }
        
        return text;
    }

    public static String getLocale() {
        return singleton.cachedProps.getProperty(KEY_LOCALE);
    }

    public static void setLocale(String locale) {
        singleton.cachedProps.setProperty(KEY_LOCALE, locale);
    }

    public static long getSyncFreq() {
        String strSyncFreq = singleton.cachedProps.getProperty(KEY_SYNC_FREQ);
        if (strSyncFreq == null) {
            return Constants.SYNC_FREQ_5_MIN;
        } else {
            long lSyncFreq = Constants.SYNC_FREQ_5_MIN;
            try {
                lSyncFreq = Long.parseLong(strSyncFreq);
            } catch (Exception ex) {
                logger.error(ex);
            }
            
            return lSyncFreq;
        }
    }

    public static void setSyncFreq(long syncFreq) {
        singleton.cachedProps.setProperty(KEY_SYNC_FREQ, String.valueOf(syncFreq));
    }

    public static String[] getRecentUserList() {
    	//
        String value = singleton.cachedProps.getProperty(KEY_USER_LIST);
        if (value == null || "".endsWith(value)) {
            return null;
        } else {
            return value.split(SPLIT_SYMBOL);
        }
    }
    
    public static void updateLatestUserInfo(String userName, String password) {
        
        if (userName == null) {
            setProperty(KEY_LAST_USER_NAME, "");
        } else {
            setProperty(KEY_LAST_USER_NAME, userName);
            tryAddUser(userName);
            
            if (password != null && !"".equals(password)) {
                setProperty(getUserPasswordKey(userName), FreeDoitDataUtils.hashString(password));
            }
        }
    }
    
    public static String getLatestUser() {
        return getProperty(KEY_LAST_USER_NAME);
    }
    
    public static String getUserPassword(String userName) {
        if (userName == null || "".equals(userName)) {
            return null;
        } else {
            return getProperty(getUserPasswordKey(userName));
        }
    }
    
    private static String getUserPasswordKey(String userName) {
        return FreeDoitDataUtils.hashString(userName + ".password");
    }
}
